<template>
  <div class="bg-blue-100 flex flex-col w-full  justify-start">
    <!-- <textarea spellcheck="false" readonly="readonly" ref="outputArea" class="resize-none px-4 py-2 custom-scrollbar bg-[rgb(255, 255, 255)] h-full w-full text-[15px] text-black-800 text-left preline " :value="showValue">
    </textarea > -->
    <div v-html="showValue" class="custom-scrollbar overflow-scroll"></div>
    </div>
</template>

<script>
import bus from '@/utils/bus.js'
export default {
  name: 'ViewComponent',
  components:{
        // SearchComponent
  },
  props: {
    dataShow: {
      type: String,
      required: true,
    },
    highLightkeyWordProp: {
      type: String,
      required : true,
    }
  },
  data(){
    return {
      storageValue :"",
      showValue:"",

      searchKeyword: '', // 搜索关键词
      highLightKeyWord : '',
      matchPositions: [], // 存储匹配到的文本位置信息
      currentMatchIndex: -1, // 当前高亮的匹配项索引
      matchCount: 0, // 匹配到的总数量
    };
  },
  watch:{
    highLightkeyWordProp(newValue) {
      this.highLightKeyWord = newValue
      console.log('highlight keyword: ', this.highLightKeyWord)
      this.handleHighLightKeyWord()
    },  
    dataShow(newValue) {
      this.storageValue += newValue
      const filteredData = this.handleHighLightKeyWord()
      // const filteredData = this.keyWordFilter(this.storageValue, this.searchKeyword)
      this.showValue = filteredData
      this.scrollToBottom();
    }
  },
  mounted(){
    bus.$on('filterKeyword', res=>{
      console.log('handle search key word', res)
      this.handleSearchKeyWord(res)
    })
  },
  methods:{
    handleSearchKeyWord(data){
      this.searchKeyword = data
      // this.showValue = this.keyWordFilter(this.storageValue, this.searchKeyword)
      // console.log('this.showValue:', this.showValue)
    },
    scrollToBottom() {
    this.$nextTick(() => {
      const textarea = this.$refs.outputArea;
      if (textarea) {
        textarea.scrollTop = textarea.scrollHeight;
        }
      });
    },
    
  keyWordFilter(longText, keyword) {
    if (!keyword) return longText;
    const lines = longText.split(/\r?\n/);
    let matches = "";

    const lowerKeyword = keyword.toLowerCase();
    for (const line of lines) {
      if (line.toLowerCase().includes(lowerKeyword)) {
          matches +=  line + "\r\n";
      }
    }
    return matches;
  },

  handleHighLightKeyWord(){
    if(this.highLightKeyWord.length == 0) {
      return this.storageValue
    }
    const matchesIndex = this.findAllMatches(this.storageValue, this.highLightKeyWord, false)
    console.log("matches: ", matchesIndex)
    const highlightedText = this.highLightFunc(matchesIndex, this.storageValue)
    console.log('highlightedText', highlightedText)
    return highlightedText
  },

  findAllMatches(longStr, shortStr, caseSensitive = true) {
    if (!shortStr) return []; 
    console.log('shortStr ', shortStr)
    const escapedShortStr = shortStr.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    console.log('escapedShortStr ', escapedShortStr)
    const flags = caseSensitive ? 'g' : 'gi';
    const regex = new RegExp(escapedShortStr, flags);
    
    const matches = [];
    let match;
    
    // 使用 exec 方法循环查找所有匹配
    while ((match = regex.exec(longStr)) !== null) {
      console.log('match')
      matches.push({
        start: match.index,
        end: match.index + match[0].length
      });
    }
    return matches;
  },
  highLightFunc(matchesIndex, longText){
    let result = '';
    let end = 0;
    const count = matchesIndex.length
    for(let i = 0; i < count; i++) {
      const start = matchesIndex[i].start
      if(result.length == 0) {
        result += longText.substring(0, start)
      }
      if(end < start && end != 0) {
        result += longText.substring(end, start)
      }
      end = matchesIndex[i].end

      result += `<mark class="bg-yellow-200">`
      result += longText.substring(start, end)
      result += `</mark>`
    }
    return result
  }

  }
}
</script>

<style scoped>
.preline{
  white-space: pre-line;
}

.custom-scrollbar::-webkit-scrollbar {
  width: 10px;
  box-sizing: border-box;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
  margin-top: 2px; 
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 10px;
  /* margin-bottom: 50px; */
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background: #555;
}

</style>